package com.shanghaionstar.dealersorder;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;

import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.framework.annotation.ContentView;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.mag.dealer.MaintenanceDealerResponseEntity;
import com.onstar.cn.weight.DeleteEditText;
import com.shanghaionstar.R;
import com.shanghaionstar.dealersorder.bean.OrderDealerRequestEntity;
import com.shanghaionstar.dealersorder.presenter.OrderPresenter;
import com.shanghaionstar.dealersorder.view.OrderView;
import com.shanghaionstar.swipe.SwipeActivity;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.ApplicationUtil;

import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 经销商预约信息提交操作页面
 * Created by Yonglang Hong on 2016/8/12.
 */
@ContentView(R.layout.onstar_dealer_booking_info)
public class OrderActivity extends SwipeActivity implements View.OnClickListener, OrderView {

    @FindViewById
    private TextView text_vehicle_info_content;
    @FindViewById
    private TextView text_dealer_info_content;
    @FindViewById
    private Spinner dealer_type_selecter;
    @FindViewById
    private DeleteEditText edit_booking_preson_info;
    @FindViewById
    private DeleteEditText edit_booking_phone_info;
    @FindViewById
    private TextView edit_booking_time_info;

    private ArrayAdapter<String> mAdapter;

    private String[] mStringArray;

    private ProgressDialog dialog;

    private int year, month, day;

    private DatePickerDialog pickerDialog;

    private MaintenanceDealerResponseEntity dealerBean;

    private OrderDealerRequestEntity requestEntity;

    private OrderPresenter orderPresenter;

    public OrderPresenter getOrderPresenter() {
        if (orderPresenter == null) {
            orderPresenter = new OrderPresenter(getScheduler(), this);
            orderPresenter.setOrderView(this);
        }
        return orderPresenter;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    private void init() {
        initOrderType();
        setUpViews();
    }

    private void setUpViews() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            dealerBean = (MaintenanceDealerResponseEntity) bundle.getSerializable("dealerResponse");
            if (dealerBean != null)
                text_dealer_info_content.setText(dealerBean.getName());
        }
        text_vehicle_info_content.setText(ApplicationUtil.getInstance().getCarInfo());
        Calendar calendar = Calendar.getInstance(Locale.CHINA);
        calendar.setTime(new Date(System.currentTimeMillis()));
        calendar.add(Calendar.DAY_OF_MONTH, +2);
        year = calendar.get(Calendar.YEAR); //获取Calendar对象中的年
        month = calendar.get(Calendar.MONTH);//获取Calendar对象中的月
        day = calendar.get(Calendar.DAY_OF_MONTH);//获取这个月的第几天
        edit_booking_time_info.setText(year + "-" + (month + 1) + "-" + day);
    }

    @OnClick({R.id.edit_booking_time_info, R.id.btn_commit_booking_info})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.edit_booking_time_info:
                chooseDate();
                break;
            case R.id.btn_commit_booking_info:
                commitOrderSafety();
                break;
        }
    }

    /**
     * 若信息符合要求，则做提交请求
     */
    private void commitOrderSafety() {
        if (isValid())
            commitOrder();
    }

    private void commitOrder() {
        showLoadProgress();
//        BusinessUtil.sendReportByClickType(this, FunctionNameFindId.Dealer_Submit.getStringValue());
        getOrderPresenter().commitOrder(requestEntity);
    }

    /**
     * 校验提交信息是否符合要求
     *
     * @return
     */
    private boolean isValid() {
        requestEntity = new OrderDealerRequestEntity();
        String bookingPerson = edit_booking_preson_info.getText().toString().trim();
        String bookingPhone = edit_booking_phone_info.getText().toString().trim();
        String bookingTime = edit_booking_time_info.getText().toString().trim();
        if (CommonUtil.isNull(bookingPerson)) {
            AlertDialogUtil.showAlertDialog(this, R.string.dialog_warning, R.string.hini_book_person);
            return false;
        }
        if (CommonUtil.isNull(bookingPhone)) {
            AlertDialogUtil.showAlertDialog(this, R.string.dialog_warning, R.string.hini_book_phone);
            return false;
        } else if (!isMobileNum(bookingPhone)) {
            AlertDialogUtil.showAlertDialog(this, R.string.dialog_warning, R.string.hini_book_phone_matcher);
            return false;
        }
        if (CommonUtil.isNull(bookingTime)) {
            AlertDialogUtil.showAlertDialog(this, R.string.dialog_warning, R.string.hini_book_time);
            return false;
        } else {
            Calendar calendar = Calendar.getInstance();
            calendar.set(year, month, day);
            long time = calendar.getTime().getTime() - new Date().getTime();
            if (time < 2 * 24 * 60 * 60 * 1000) {
                AlertDialogUtil.showAlertDialog(this, R.string.dialog_warning, R.string.hini_book_time_greater);
                return false;
            }
        }
        requestEntity.setOrderName(bookingPerson);
        requestEntity.setOrderPhone(bookingPhone);
        requestEntity.setOrderTime(bookingTime);
        requestEntity.setOrderType(mStringArray[dealer_type_selecter.getSelectedItemPosition()]);
        requestEntity.setServiceCode(dealerBean.getServiceCode());
        return true;
    }

    /**
     * @Description: 验证手机号的格式是都正确
     */
    public static boolean isMobileNum(String content) {
        String reg = "^(0|86|17951)?(13[0-9]|15[0-9]|17[0-9]|18[0-9]|14[0-9])[0-9]{8}$";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(content);
        return matcher.find();
    }

    private void showLoadProgress() {
        if (dialog == null) {
            dialog = new ProgressDialog(this);
            dialog.setMessage(getString(R.string.waiting));
        }
        dialog.show();
    }

    private void hideLoadProgress() {
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    /**
     * 选择日期
     */
    private void chooseDate() {
        if (pickerDialog == null) {
            DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int myyear, int monthOfYear, int dayOfMonth) {
                    year = myyear;
                    month = monthOfYear;
                    day = dayOfMonth;
                    //更新日期
//                    BusinessUtil.sendReportByClickType(OrderActivity.this, FunctionNameFindId.Dealer_Date.getStringValue());
                    updateDate();
                }

                private void updateDate() {
                    edit_booking_time_info.setText(year + "-" + (month + 1) + "-" + day);
                }
            };
            pickerDialog = new DatePickerDialog(this, dateSetListener, year, month, day);
        }
        pickerDialog.show();
    }

    private void initOrderType() {
        mStringArray = getResources().getStringArray(R.array.book_type);
        // 使用自定义的ArrayAdapter
        mAdapter = new CustomArrayAdapter(this, mStringArray);
        // 设置下拉列表风格(这句不写也行)
        mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        dealer_type_selecter.setAdapter(mAdapter);
    }

    public class CustomArrayAdapter extends ArrayAdapter<String> {
        private Context mContext;
        private String[] mStringArray;

        public CustomArrayAdapter(Context context, String[] stringArray) {
            super(context, android.R.layout.simple_spinner_item, stringArray);
            mContext = context;
            mStringArray = stringArray;
        }

        @Override
        public View getDropDownView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater inflater = LayoutInflater.from(mContext);
                convertView = inflater.inflate(android.R.layout.simple_spinner_dropdown_item, parent, false);
                convertView.setBackground(mContext.getResources().getDrawable(R.drawable.onstar_spinner_bg));
            }
            TextView tv = (TextView) convertView.findViewById(android.R.id.text1);
            tv.setText(mStringArray[position]);
            tv.setBackground(mContext.getResources().getDrawable(R.drawable.onstar_spinner_down_item_bg));
            tv.setTextSize(18f);
            tv.setGravity(Gravity.RIGHT | Gravity.CENTER);
            tv.setTextColor(Color.BLACK);
            return convertView;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater inflater = LayoutInflater.from(mContext);
                convertView = inflater.inflate(android.R.layout.simple_spinner_item, parent, false);
            }
            TextView tv = (TextView) convertView.findViewById(android.R.id.text1);
            tv.setText(mStringArray[position]);
            tv.setTextSize(18f);
            tv.setPadding(0, 0, 60, 0);
            tv.setGravity(Gravity.RIGHT | Gravity.CENTER);
            tv.setTextColor(Color.BLACK);
            return convertView;
        }
    }


    @Override
    public void showOrderInfo(String num) {
        hideLoadProgress();
//        BusinessUtil.sendReportByClickType(OrderActivity.this, FunctionNameFindId.Dealer_Booking_Success.getStringValue());
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setMessage("您已预约成功，订单号为：\n" + num + "\n经销商会在48h内给您回电")
                .setPositiveButton("返回首页", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                })
                .setNegativeButton("预约记录", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startActivity(new Intent(OrderActivity.this, OrderRecordActivity.class));
                        finish();
                    }
                })
                .setCancelable(true);
        builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                return keyCode == KeyEvent.KEYCODE_BACK;
            }
        });
        builder.show();
    }

    @Override
    public void showOrderFailed() {
        hideLoadProgress();
        AlertDialogUtil.showAlertDialog(this, R.string.dialog_warning, R.string.DR_ERR001);
    }

    @Override
    public void showErr(Throwable throwable) {
        hideLoadProgress();
        if (throwable instanceof HttpException)
            AlertDialogUtil.showDialogByExceptionCode(this, (HttpException) throwable);
    }

    @Override
    public BasePresenter getPresenter() {
        return null;
    }
}
